package com.yedou.controller;

import cn.hutool.core.bean.BeanUtil;
import com.yedou.common.Result;
import com.yedou.entity.dto.PeopleDto;
import com.yedou.entity.po.People;
import com.yedou.message.RegisterMessage;
import com.yedou.produce.RocketMQProducer;
import com.yedou.service.IPeopleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/mq")
@Api(tags = "消息队列")
public class MqController {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private IPeopleService peopleService;


    @ApiOperation("测试消息队列")
    @PostMapping("/pushMessage")
    public Result<Boolean> get(@RequestParam("id") int id) {
        rocketMQTemplate.convertAndSend("first-topic","你好,Java旅途" + id);
        return Result.ok(true);
    }


    // 发送对象消息
    @ApiOperation("发送对象消息")
    @PostMapping("/pushObjectMessage")
    public Result<Boolean> pushObjectMessage(@RequestParam("id") Long id) {
        People people = new People();
        people.setId(id);
        people.setUsername("用户" + id);
        // 发送对象消息，会自动序列化为JSON
        rocketMQTemplate.convertAndSend("user-topic", people);
        return Result.ok(true);
    }

    /**
     * 用户注册接口
     */
    @ApiOperation("用户注册接口")
    @PostMapping("/register")
    public Result<Boolean> register(@RequestBody PeopleDto peopleDto){
        // 1.注册
        People people = BeanUtil.copyProperties(peopleDto, People.class);
        peopleService.save(people);

        // 2. 创建注册成功消息
        RegisterMessage message = new RegisterMessage();
        message.setUserId(people.getId());
        message.setUsername(people.getUsername());
        message.setEmail("12131290@qq.com");
        message.setRegisterTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        // 3. 发送异步消息到RocketMQ，无需等待邮件发送完成
        rocketMQTemplate.convertAndSend("user-register-topic", message);

        // 4. 立即返回注册成功，用户可以直接登录
        return Result.ok(200,"注册成功，请登录",true);
    }



    @Autowired
    private RocketMQProducer rocketMQProducer;

    @RequestMapping("/send")
    @ResponseBody
    public SendResult send(String msg)  {
        //formats: `topicName:tags`
        return rocketMQProducer.sendMsg(msg);
    }

}
